package cyclestats

import (
	"context"
	"go.mongodb.org/mongo-driver/mongo"
	"go.mongodb.org/mongo-driver/mongo/options"
	"go.mongodb.org/mongo-driver/mongo/readpref"
	"go.mongodb.org/mongo-driver/x/mongo/driver/connstring"
	"kratos-layout/pkg/logger"
	"time"
)

// Data .
type Data struct {
	DB     *mongo.Database
	Client *mongo.Client
}

// NewData .
func NewData(dbUri string) (*Data, error) {
	conn, err := connstring.Parse(dbUri)
	if err != nil {
		logger.Errorf("NewData DB uri parse error: %v", err)
		return nil, err
	}

	db, client, err := MongoConnect(dbUri, conn.Database)
	if err != nil {
		logger.Errorf("MongoConnect error: %v", err)
		return nil, err
	}

	return &Data{DB: db, Client: client}, nil
}

func MongoConnect(uri, dbname string) (*mongo.Database, *mongo.Client, error) {
	ctx, cancel := context.WithTimeout(context.TODO(), 10*time.Second)
	defer cancel()
	client, err := mongo.Connect(ctx, options.Client().ApplyURI(uri))
	if err != nil {
		return nil, nil, err
	}
	ctxPing, cancel := context.WithTimeout(ctx, 5*time.Second)
	defer cancel()
	err = client.Ping(ctxPing, readpref.Primary())
	if err != nil {
		return nil, nil, err
	}
	db := client.Database(dbname)

	return db, client, nil
}
